const RoleDB = require("../../services/role/RoleDB.js");

const RoleController = {
  async getRoleList(req, res) {
    try {
      let result = await RoleDB.getRoleList(req.query);
      let count = await RoleDB.getCount();
      res.send({
        code: 200,
        message: "获取角色列表成功",
        data: result,
        totalCount: count,
      });
    } catch (error) {
      res.send({
        code: -1,
        message: "获取角色列表失败",
      });
    }
  },
  async deleteRoleListItem(req, res) {
    try {
      let result = await RoleDB.deleteRoleListItem(req.params.id);
      if (result.deletedCount === 1) {
        res.send({
          code: 200,
          message: "删除成功",
        });
      } else {
        res.send({
          code: -1,
          message: "删除失败",
        });
      }
    } catch (error) {}
  },
  async addRoleList(req, res) {
    try {
      // 默认数据
      let initState = {
        createtime: Date.now(),
        updatetime: Date.now(),
      };
      req.body = { ...req.body, ...initState };
      // 可以在将数据操作数据库的时候进行校验数据
      let result = await RoleDB.addRoleList(req.body); //将添加成功的数据返回

      if (result) {
        res.send({
          code: 200,
          message: "添加成功",
        });
      } else {
        throw "添加失败";
      }
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
  // 前端传入编辑的时间
  async updateRoleItem(req, res) {
    try {
      let result = await RoleDB.updateRoleItem(req.params.id, req.body);
      if (result) {
        res.send({
          code: 200,
          message: "更新角色信息成功",
          result,
        });
      } else {
        throw "更新角色信息失败";
      }
    } catch (error) {
      res.send({
        code: -1,
        message: error,
      });
    }
  },
};

module.exports = RoleController;
